/**
 * 
 */
package com.cipe.cmrs.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.cipe.cmrs.bean.AuditsBean;
import com.cipe.cmrs.bean.CipeprojectBean;
import com.cipe.cmrs.model.Audits;
import com.cipe.cmrs.model.Cipeproject;

/**
 * @author Incepio
 * 
 */
@Service
public class AuditsService extends BaseService<Audits> {
	@Autowired
	private ConversionService conversionService;
	@Autowired
	private CipeprojectService cipeprojectService;

	@Transactional(readOnly = true)
	public List<Audits> findallAudits(String procedure) {
		return this.dao.getResultListWithNativeQuery(procedure, Audits.class);
	}

	@Transactional
	public AuditsBean save(AuditsBean bean) {
		Audits audits = conversionService.convert(bean, Audits.class);
		Cipeproject cipeproject = cipeprojectService.findById(bean.getProject()
				.getId());
		audits.setCipeproject(cipeproject);
		audits = dao.merge(audits);
		cipeproject.setAudits(audits);
		return conversionService.convert(audits, AuditsBean.class);
	}

	public AuditsBean getAuditByProjectId(Integer cipeprojectId) {
		Assert.notNull(cipeprojectId);
		AuditsBean bean = null;

		String sqlQuery = "FROM Audits WHERE cipeproject.id = ?";
		Audits audits = dao.getSingleResult(sqlQuery,
				new Object[] { cipeprojectId });
		if (audits != null) {
			Cipeproject cp = cipeprojectService
					.getParentProjectStartandEndDates(cipeprojectId);
			bean = conversionService.convert(audits, AuditsBean.class);
			try {
				bean.setProjectStartDate(cp.getProjectStartDate());
				bean.setProjectEndDate(cp.getProjectEndDate());
			} catch (NullPointerException e) {
			}
			bean.setProject(conversionService.convert(audits.getCipeproject(),
					CipeprojectBean.class));
		} else {
			Cipeproject cipeproject = cipeprojectService
					.findById(cipeprojectId);
			bean = new AuditsBean();
			try {
				bean.setProjectStartDate(cipeproject.getProjectStartDate());
				bean.setProjectEndDate(cipeproject.getProjectEndDate());
			} catch (NullPointerException e) {
			}
			bean.setProject(conversionService.convert(cipeproject,
					CipeprojectBean.class));
		}

		return bean;
	}
}
